// window.onload = function() {

// debounce(gopage(1, 10), 500)

function gopage(page, pagesize) {
    try {
        console.log('gopage');
        // var data = await jqAjax("GET", "/questions/", {
        //         page: page,
        //         pagesize: pagesize
        //     })
            // getData(page, pagesize).then(function(res) {
            //     if(res.page)
            // })
        console.log(data);
        // 表格所有行数(所有记录数)
        var num = data.counts;
        // 总页数
        var totalPage = data.pages;
        // 每页显示行数
        var pageSize = pagesize;
        // 当前的页数
        var currentPage = data.page;
        // 每页的第一行
        var startRow = (currentPage - 1) * pageSize + 1;
        // 每页的最后一行
        var endRow = currentPage * pageSize;
        endRow = (endRow > num) ? num : endRow;
        //渲染分页
        console.log(currentPage);
        let tempStr = "共" + num + "条记录 分" + totalPage + "页 当前第" + currentPage + "页 ";
        if (currentPage > 1) {
            tempStr += "<a href=javasrcipt:; class='homePage'>首页</a>";
            tempStr += "<a href=javascript:; class='previousPage '><上一页</a>";
            document.querySelector('.paging').innerHTML = tempStr;
            document.querySelector('.homePage').addEventListener('click', function() {
                getData(1, pageSize)
                window.location.reload(true)
            })
            document.querySelector('.previosPage').addEventListener('click', function() {
                getData((currentPage - 1), pageSize)
                window.location.reload(true)
            })
        } else {
            tempStr += "首页";
            tempStr += "<上一页";
            document.querySelector('.paging').innerHTML = tempStr;
        }

        if (currentPage < totalPage) {
            tempStr += "<a href=javascript:; class='nextPage'>下一页></a>";
            tempStr += "<a href=javascript:; class='lastPage'>尾页</a>";
            document.querySelector('.paging').innerHTML = tempStr;
            document.querySelector('.nextPage').addEventListener('click', function() {
                getData((currentPage + 1), pageSize)
                console.log(currentPage);
                window.location.reload(true)
            })
            document.querySelector('.lastPage').addEventListener('click', function() {
                getData(totalPage, pageSize)
                window.location.reload(true)
            })
        } else {
            tempStr += "下一页>";
            tempStr += "尾页";
            document.querySelector('.paging').innerHTML = tempStr;
        }
        console.log(tempStr);


    } catch (error) {
        console.log(error);
    }
}

async function getData(page, pagesize) {
    console.log(page);
    var tbody = document.querySelector('tbody');
    console.log(tbody);
    try {
        var data = await jqAjax("GET", "/questions/", {
            page: page,
            pagesize: pagesize
        })
        console.log(data);
        //渲染表格
        for (let i = 0; i < data.items.length; i++) {
            //获取服务端的id
            let dataId = [];
            dataId = data.items[i].id;
            //动态创建tr
            let tr = document.createElement('tr');
            //动态创建td并从服务端获取数据渲染到页面
            let directionTd = document.createElement('td');
            directionTd.innerHTML = data.items[i].direction;
            let questionTypeTd = document.createElement('td');
            questionTypeTd.innerHTML = data.items[i].questionType;
            let buttonTd = document.createElement('td');
            buttonTd.innerHTML = '<button class="edit" id=' + dataId + '>编辑</button> <button class="remove" id=' + dataId + '>删除</button>'

            tr.appendChild(directionTd);
            tr.appendChild(questionTypeTd);
            tr.appendChild(buttonTd);

            tbody.appendChild(tr);

            // 表格变色
            var trs = document.querySelector('tbody').querySelectorAll('tr');
            for (var j = 0; j < trs.length; j++) {
                trs[i].onmouseover = function() {
                    this.className = 'change';
                }
                trs[i].onmouseout = function() {
                    this.className = '';
                }
            }
            //利用id删除tr
            var removebtn = document.querySelectorAll('.remove');
            removebtn[i].addEventListener('click', function() {
                clickRemove(this.id)
            })

            //编辑
            //编辑弹框显示
            var editbtn = document.querySelectorAll(".edit");
            editbtn[i].addEventListener('click', function() {
                    document.querySelector('.add').style.display = 'block';
                })
                //关闭弹窗按钮
            var close = document.querySelector('.close');
            close.addEventListener('click', function() {
                    document.querySelector('.add').style.display = 'none'
                    window.location.reload(true);
                })
                //点击上传
            var uploadEdit = document.querySelector('.uploadEdit');
            var editId = document.querySelectorAll('.edit').id;
            console.log(uploadEdit);
            uploadEdit.addEventListener('click', function() {
                console.log('id:' + editId);
                clickEdit(editId);
            })
        }
        return data

    } catch (error) {
        console.log(error);
    }

}
// throttle(getData(1, 10), 500)

//包装删除函数
function clickRemove(id) {
    var agin = confirm("再想想 确定删除吗");
    if (agin === true) {
        async function removeData(id) {
            console.log('async');
            try {
                let data = await jqAjax("DELETE", "/questions/" + id, JSON.stringify({ id: id }))
                window.location.reload(true);
            } catch (error) {
                console.log('删除错误');
                console.log(error);
            }
        }
        debounce(removeData(id), 500)
    }
}

//编辑
//动态改变下拉框 用JSON
async function getSubject() {
    let subject = await jqAjax("GET", "/static/data/subject.json")
    console.log('动态JSON:' + subject.subject);
    var option = subject.subject;
    //渲染到页面
    for (var i = 0; i < subject.subject.length; i++) {
        $("select").prepend('<option>' + option[i].name + '</option>');
    }
}
getSubject();
// 包装编辑函数
function clickEdit(id) {
    console.log('学科类型: ' + $("select").find("option:selected").val());
    console.log('题型' + $("input[name='questionType']:checked").val());
    async function insertData() {
        var fd = new FormData();
        fd.append("img", $("#file").prop("files")[0]);
        var imgUrl;
        $.ajax({
            type: 'POST',
            url: 'http://www.liulongbin.top:3006/api/upload/avatar',
            data: fd,
            contentType: false,
            processData: false,
            async: false,
            success: function(data) {
                if (data.status == 200) {
                    console.log('成功上传文件');
                    imgUrl = 'http://www.liulongbin.top:3006' + data.url
                    $(".img").show()
                    $('img').prop('src', imgUrl)

                } else {
                    console.log('失败');
                }
            },
            error: function(xhr, status, error) {
                console.log('error');
                console.log(xhr);
                console.log(status);
                console.log(error);
            }
        })
        try {
            let data = await jqAjax("PUT", "/questions/" + id, JSON.stringify({
                direction: $("select").find("option:selected").val(),
                options: [{
                    code: "a",
                    img: imgUrl,
                    title: "title",
                    isRight: "0"
                }],
                questionType: $("input[name='questionType']:checked").val()
            }))
        } catch (error) {
            console.log("catch出错");
            console.log(error);
        }
    }
    debounce(insertData(), 500)
}

// }